package org.jxy.study.rpc.config;

import org.jxy.study.rpc.message.ErrorCodeEnums;
import org.jxy.study.rpc.message.Request;
import org.jxy.study.rpc.message.Response;
import org.jxy.study.rpc.netty.NettyClient;
import org.jxy.study.rpc.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;

/**
 * @author : porteryao
 * @description : Rpc代理工厂
 * @date : 2021/3/11 11:14
 */
@Component
public class RpcFactory implements InvocationHandler {

    @Autowired
    NettyClient client;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getDeclaringClass() == Object.class) {
            logger.info("method:{}代理执行,为Object声明的不进行代理执行", method.getName());
            return method.invoke(proxy, args);
        }
        logger.info("method:{}代理执行", method.getName());
        Request request = new Request();
        request.setClassName(method.getDeclaringClass().getName());
        request.setMethodName(method.getName());
        request.setParameters(args);
        request.setParameterTypes(method.getParameterTypes());
        request.setId(UUID.randomUUID().toString());
        Response response = client.sendMsg(request);
        Class<?> returnType = method.getReturnType();
        //返回错误
        if (response.getCode() == ErrorCodeEnums.FAIL.getCode()) {
            throw new Exception(response.getErrorMsg());
        }
        /*
         *1.返回结果是基础类型或者String类型，直接返回
         *2.其他类型转换为该类型
         */
        if (returnType.isPrimitive() || String.class.isAssignableFrom(returnType)) {
            return response.getData();
        } else if (Collection.class.isAssignableFrom(returnType)) {
            return JsonUtil.jsonStringToObject(response.getData().toString(), Object.class);
        } else if (Map.class.isAssignableFrom(returnType)) {
            return JsonUtil.jsonStringToObject(response.getData().toString(), Map.class);
        } else {
            Object data = response.getData();
            return JsonUtil.jsonStringToObject(data.toString(), returnType);
        }
    }
}
